package com.rcd.viatornisl.android;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.widget.Toast;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.gson.Gson;
import com.rcd.viatornisl.android.model.InterestManager;

public class LoadingActivity extends Activity {
	
	private int _MaxAttempts = 5;
	private boolean _IsLoaded = false;
	private Handler _Handler = new Handler();
	public static final String INTERESTS_STATE = "interests";
	
	private boolean isNetworkAvailable() {
		// Create a connectivity manager
	    ConnectivityManager connectivityManager = ((ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE));
	    
	    // Create a network info
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    
	    // Provide the return
	    return ((activeNetworkInfo != null) && (activeNetworkInfo.isConnected()));
	}
	
	@Override
	protected void onStart() {
		// Default operations
		super.onStart();
		
		// Track with Google Analytics
		EasyTracker.getInstance().activityStart(this);
	}
	
	@Override
	protected void onStop() {
		// Default operations
		super.onStop();

		// Untrack with Google Analytics
		EasyTracker.getInstance().activityStop(this);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// Default operations
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.loading_activity);
					
		// Post an execution
		this._Handler.post(new Runnable() {
			
			@Override
			public void run() {
				// Execution loop and check if this is not loaded
				if ((LoadingActivity.this._MaxAttempts-- > 1) && (!(LoadingActivity.this._IsLoaded))) {
					// Check the network
					if (LoadingActivity.this.isNetworkAvailable()) {
						// Load the interests
						InterestManager.InterestListThread interestThread = new InterestManager.InterestListThread(LoadingActivity.this.getString(R.string.base_url), true);											
						
						// If not null
						if (interestThread.getInterests() != null) {
							// Get the shared preferences object
							SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoadingActivity.this);
							
							// Edit the preferences. Set the content as JSON
							sharedPreferences.edit().putString(INTERESTS_STATE, new Gson().toJson(interestThread.getInterests())).commit();															
							
							// Start an activity
							LoadingActivity.this.startActivity(new Intent(LoadingActivity.this, StartActivity.class));
							
							// Set the is loaded flag
							LoadingActivity.this._IsLoaded = true;
						} else {
							// Create a toast object
							Toast toast = Toast.makeText(LoadingActivity.this, String.format("Tentativa: %d. %s", LoadingActivity.this._MaxAttempts, LoadingActivity.this.getString(R.string.unavailable_error_message)), Toast.LENGTH_SHORT);
							toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
							toast.show();
						}																														
					} else {
						// Create a toast object
						Toast toast = Toast.makeText(LoadingActivity.this, String.format("Tentativa: %d. %s", LoadingActivity.this._MaxAttempts, LoadingActivity.this.getString(R.string.internet_connection_error_message)), Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
						toast.show();
					}
					
					// Wait 3 seconds
					LoadingActivity.this._Handler.postDelayed(this, 3000);									
				} else {
					// Close the activity
					LoadingActivity.this.finish();
				}							
			}
			
		});				
	}	
	
}
